package controller

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/httpserver"
	"go-fox-edge-kernel-manager/utils/PageUtils"
	"strconv"
	"strings"
)

type deviceValueExTaskController struct {
}

func (e *deviceValueExTaskController) init() {
	httpserver.Server.POST("/device/value/ex/task/entities", e.selectEntityList)
	httpserver.Server.POST("/device/value/ex/task/page", e.selectPageList)
	httpserver.Server.GET("/device/value/ex/task/entity", e.queryEntity)
	httpserver.Server.POST("/device/value/ex/task/entity", e.insertEntity)
	httpserver.Server.PUT("/device/value/ex/task/entity", e.updateEntity)
	httpserver.Server.DELETE("/device/value/ex/task/entity", e.deleteEntity)

	httpserver.Server.DELETE("/device/value/ex/task/entities", e.deleteEntityList)
}

func (e *deviceValueExTaskController) selectEntityList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.selectList(context, body, false)
}

func (e *deviceValueExTaskController) selectPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.selectList(context, body, true)
}

func (e *deviceValueExTaskController) selectList(context httpserver.Context, body map[string]interface{}, isPage bool) (interface{}, error) {
	entityList := commEntityManager.FindEntityList(edgeEntity.Type.DeviceValueExTaskEntity.Type(), func(value commEntity.IEntity) bool {
		entity := value.(*edgeEntity.DeviceValueExTaskEntity)

		result := true

		if Map.Has(body, "keyword") {
			result = result && strings.Count(entity.TaskName, body["keyword"].(string)) > 0
		}

		return result
	})

	// 获得分页数据
	if isPage {
		return PageUtils.GetPageList(entityList, body), nil
	} else {
		return commEntity.BuildMapList(entityList), nil
	}
}

func (e *deviceValueExTaskController) queryEntity(context httpserver.Context) (interface{}, error) {
	str := context.Query("id")
	if str == "" {
		return nil, errors.New("输入的id为null")
	}

	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return nil, err
	}

	exist := commEntityManager.GetEntityById(edgeEntity.Type.DeviceValueExTaskEntity.Type(), id)
	if exist == nil {
		return nil, errors.New("实体不存在")
	}

	return commEntity.BuildMap(exist), nil
}

func (e *deviceValueExTaskController) insertEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	delete(body, "id")
	return e.insertOrUpdate(context, body)
}

func (e *deviceValueExTaskController) updateEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.insertOrUpdate(context, body)
}

func (e *deviceValueExTaskController) insertOrUpdate(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	// 提取业务参数
	taskName := Map.GetString(body, "taskName", "")
	taskParam := Map.GetMap(body, "taskParam", nil)

	// 简单校验参数
	if Method.HasNull(taskName, taskParam) {
		return nil, errors.New("参数不能为空: taskName, taskParam")
	}

	// 构造作为参数的实体
	entity := edgeEntity.Type.DeviceValueExTaskEntity.Instance()
	entity.TaskName = taskName
	entity.TaskParam = taskParam

	// 新增/修改实体：参数不包含id为新增，包含为修改
	if !Map.Has(body, "id") {
		exist, err := commEntityManager.GetEntityByServiceKey(entity.Type(), entity.MakeServiceKey())
		if err != nil {
			return nil, err
		}
		if exist != nil {
			return nil, errors.New("实体已存在")
		}

		err = commEntityManager.InsertEntity(entity)
		if err != nil {
			return nil, err
		}

		return nil, nil
	} else {
		id := Map.GetInt64(body, "id", 0)

		exist := commEntityManager.GetEntityById(entity.Type(), id)
		if exist == nil {
			return nil, errors.New("实体不存在")
		}

		// 修改数据
		entity.BaseEntity.Id = id
		entity.GetBaseEntity().CreateTime = exist.GetBaseEntity().CreateTime
		entity.GetBaseEntity().UpdateTime = exist.GetBaseEntity().UpdateTime
		return nil, commEntityManager.UpdateEntity(entity)
	}
}

func (e *deviceValueExTaskController) deleteEntity(context httpserver.Context) (interface{}, error) {
	str := context.Query("id")
	if str == "" {
		return nil, errors.New("输入的id为null")
	}

	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return nil, err
	}

	exist := commEntityManager.GetEntityById(edgeEntity.Type.DeviceValueExTaskEntity.Type(), id)
	if exist == nil {
		return nil, errors.New("实体不存在")
	}

	err = commEntityManager.DeleteEntity(exist)
	if err != nil {
		return nil, err
	}

	return commEntity.BuildMap(exist), nil
}

func (e *deviceValueExTaskController) deleteEntityList(context httpserver.Context) (interface{}, error) {
	ids := context.Query("ids")

	idList := strings.Split(ids, ",")
	for _, str := range idList {
		if str == "" {
			continue
		}
		id, err := strconv.ParseInt(str, 10, 64)
		if err != nil {
			return nil, err
		}

		exist := commEntityManager.GetEntityById(edgeEntity.Type.DeviceValueExTaskEntity.Type(), id)
		if exist == nil {
			return nil, errors.New("实体不存在")
		}

		err = commEntityManager.DeleteEntity(exist)
		if err != nil {
			return nil, err
		}
	}

	return nil, nil
}
